package com.jiajia.testclouduser.util;

import org.springframework.session.data.redis.RedisOperationsSessionRepository;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class SessionUtil {
    private String namespace = "spring:session:";
    private String creationTimeKey = "creationTime";
    private String maxInactiveIntervalKey = "maxInactiveInterval";
    private String lastAccessedTimeKey = "lastAccessedTime";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    @Resource(name = "sessionRepository")
    private RedisOperationsSessionRepository sessionRepository;

    String getSessionKey(String sessionId) {
        return this.namespace + "sessions:" + sessionId;
    }

    String getExpiredKey(String sessionId) {
        return this.namespace + "sessions:expires:" + sessionId;
    }

    String getSessionAttrKey(String key) {
        return "sessionAttr:" + key;
    }

    public Map<Object, Object> getSessionMap(String sessionId) {
        return sessionRepository.getSessionRedisOperations().boundHashOps(getSessionKey(sessionId)).entries();
    }

    public Object getAttribute(String sessionId, String key) {
        return getSessionMap(sessionId).get(getSessionAttrKey(key));
    }

    public long getCreationTime(String sessionId) {
        return (long) getSessionMap(sessionId).get(creationTimeKey);
    }

    public long getLastAccessedTime(String sessionId) {
        return (long) getSessionMap(sessionId).get(lastAccessedTimeKey);
    }

    public String getCreationTimeFormat(String sessionId) {
        return sdf.format(new Date(getCreationTime(sessionId)));
    }

    public String getLastAccessedTimeFormat(String sessionId) {
        return sdf.format(new Date(getLastAccessedTime(sessionId)));
    }

    public int getMaxInactiveInterval(String sessionId) {
        return (int) getSessionMap(sessionId).get(maxInactiveIntervalKey);
    }


}
